package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.alibaba.fastjson.JSON;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.squareup.okhttp.Request;

import java.text.DecimalFormat;
import java.util.HashMap;

import butterknife.InjectView;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.IntegralModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;

/**
 * Created by vain zhou on 2016/3/29.
 */
public class WashCarSubmitActivity extends ZJPBaseBarActivity implements View.OnClickListener {
    @InjectView(R.id.universal_toolBarRTitle)
    TextView tv_tool;
    @InjectView(R.id.tv_address_name)
    TextView name;
    @InjectView(R.id.tv_address_phone)
    TextView phone;
    @InjectView(R.id.tv_address_detail)
    TextView tv_address;
    @InjectView(R.id.layout_unmber)
    RelativeLayout unmber;
    @InjectView(R.id.delivery)
    TextView number;
    @InjectView(R.id.tv_total_money)
    TextView tv_money;
    String money;
//    @InjectView(R.id.choosetime)
//    RelativeLayout choosetime;
//    @InjectView(R.id.tv_time)
//    TextView tv_time;
    @InjectView(R.id.tv_submit_order)
    TextView sumbit;
    @InjectView(R.id.message)
    EditText message;
    @InjectView(R.id.layout_address)
    RelativeLayout address;
    @InjectView(R.id.tv_carnumber)
    TextView carnumber;
    @InjectView(R.id.ddGoldContentEt)
    EditText clearEditText;
    @InjectView(R.id.txt_jifen_detail)
    TextView  tv_jifen;
    private String getDay;
    private String getMoney;
    private String getNumber;
    private String tv_name;
    private String tv_phone;
    private String tv_eare;
    private String tv_car;
    private int num;
    private KProgressHUD hud;
    private double integration;
    private int point;
    private double priced;
    private  float total_money;
    private String price;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_washcarsumbit);
        unmber.setOnClickListener(this);
//        choosetime.setOnClickListener(this);
        sumbit.setOnClickListener(this);
        address.setOnClickListener(this);
        tv_name=getIntent().getStringExtra("name");
        tv_phone=getIntent().getStringExtra("moblie");
        tv_eare=getIntent().getStringExtra("eare");
        tv_car=getIntent().getStringExtra("carnumber");
        getDay=getIntent().getStringExtra("time");
        getMoney=getIntent().getStringExtra("money");
        tv_money.setText(getMoney);
        getNumber=getIntent().getStringExtra("unmber");
        number.setText(getNumber);
//        tv_time.setText(getDay);
        name.setText("收货人"+tv_name);
        phone.setText(tv_phone);
        tv_address.setText(tv_eare);
        carnumber.setText("车牌号："+tv_car);
        clearEditText.addTextChangedListener(textWatcher);
        setTool();
    }
    public void onResume() {
        super.onResume();
        initRequest();
    }
    private void initRequest() {
        if (AppUtil.isNetworkAvailable(this)) {
            requestGetintegral();
        } else {
            ToastUtil.showShort(WashCarSubmitActivity.this, R.string.tips_network_error);
        }
    }

    private void requestGetintegral() {
        hud = KProgressHUD.create(this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("正在加载")
                .setCancellable(true);
        hud.show();
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("mobilephone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Integration).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        hud.dismiss();
                        ToastUtil.showShort(WashCarSubmitActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        hud.dismiss();
                        LogUtil.i(TAG, "获取个人积分：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取个人积分"))) {
                            IntegralModel model = JSON.parseObject(response, IntegralModel.class);
                            //获取请求成功
                            if (model.getResult() == 0) {
                                //可用积分；
                                integration=model.getData().getPoints();
                                tv_jifen.setText(model.getData().getMoneyToPoint()+""+"积分可抵用1元"+"(可用积分为"+model.getData().getPoints()+")");
                                point=model.getData().getMoneyToPoint();
                            }
                        } else {
                            hud.dismiss();
                            ToastUtil.showShort(WashCarSubmitActivity.this, NetRequestUtil.requestsError(response, "获取个人积分"));
                            integration=0;

                        }
                    }

                });
    }
    //动态判断输入框驶入的值
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            if (!TextUtils.isEmpty(clearEditText.getText().toString())) {
                if(Double.valueOf(clearEditText.getText().toString())>integration){
                    ToastUtil.showShort(WashCarSubmitActivity.this, "积分不足");
                    sumbit.setBackgroundResource(R.drawable.bar_gary);
                    sumbit.setClickable(false);
                }else {
                    sumbit.setClickable(true);
                    if (total_money >=Double.valueOf(clearEditText.getText().toString()) /point) {
                        sumbit.setBackgroundResource(R.drawable.bar_blue);
                        priced = total_money - Double.valueOf(clearEditText.getText().toString()) / point;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        tv_money.setText("¥" + df.format(priced));
                        price=df.format(priced);
                    }else {
                        ToastUtil.showShort(WashCarSubmitActivity.this, "积分抵扣金额不可大于商品价格");
                        sumbit.setBackgroundResource(R.drawable.bar_gary);
                        sumbit.setClickable(false);
                    }
                }

            }else{
                price=20*num+"";
                tv_money.setText(price);
            }
        }
    };


    private void setTool() {
            tv_tool.setText("预约洗车");
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_unmber:
                     new MaterialDialog.Builder(this)
                             .title("选择规格")
                             .titleColor(getResources().getColor(R.color.background_material_dark))
                             .theme(Theme.LIGHT)
                             .items(R.array.washcar)
                             .itemsCallback(new MaterialDialog.ListCallback() {
                                 @Override
                                 public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                     number.setText(text);
                                     num= which+1;
                                     money=20*num+"";
                                     price =money;
                                     total_money=Float.valueOf(money);
                                     tv_money.setText(money);
                                 }
                             })
                             .positiveText(android.R.string.cancel)
                             .show();
                break;
            case R.id.choosetime:
                Intent intent = new Intent();
                intent.putExtra("name", tv_name);
                intent.putExtra("moblie",tv_phone);
                intent.putExtra("address",tv_eare);
                intent.putExtra("carnumber",tv_car);
                intent.putExtra("money",money);
                intent.putExtra("number",number.getText().toString().trim());
                intent.putExtra("type",2);
                intent.putExtra("id", 1);
                intent.setClass(WashCarSubmitActivity.this,ChooseCarTimeActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_submit_order:
                    //数据验证
                    if (isCheckInput()) {
                        if (AppUtil.isNetworkAvailable(WashCarSubmitActivity.this)) {
                            requestgoshop();
                        } else {
                            ToastUtil.showShort(WashCarSubmitActivity.this, R.string.tips_network_error);
                        }
                    }
            default:
                break;
            case R.id.layout_address:
                Intent intent1 = new Intent();
                intent1.putExtra("name",tv_name);
                intent1.putExtra("eare",tv_eare);
                intent1.putExtra("moblie",tv_phone);
                intent1.putExtra("carnumber",tv_car);
                intent1.setClass(WashCarSubmitActivity.this,AddCaraddtressActivity.class);
                startActivity(intent1);
                break;
        }

    }
    private boolean isCheckInput() {
        if (TextUtils.isEmpty(number.getText().toString().trim())) {
            Snackbar.make(clearEditText, "请选择规格", Snackbar.LENGTH_SHORT).show();

            return false;
        }
        return true;
    }

    private void requestgoshop() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("ProId",AppApplication.getInstance().getSpUtil().getID_Car());
        params.put("Quantity", 1+"");
        params.put("Remark",message.getText().toString().trim());
        params.put("BusinessType",2+"");
        params.put("Name",tv_name);
        params.put("Phone",tv_phone);
        params.put("Address",tv_eare);
        params.put("CarNo",tv_car);
//        params.put("ConsigneTime",getDay);
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.WashCar).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ToastUtil.showShort(WashCarSubmitActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "提交收获地址：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "提交订单"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "提交订单：" + model.getData());
                            if (model != null && model.getResult() == 0) {
                                //获取请求成功
                                if(price.equals("0.0")){
                                    Intent mIntentRegInfo = new Intent(WashCarSubmitActivity.this,MyorderActivity.class);
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }else {
                                    Intent mIntentRegInfo = new Intent(WashCarSubmitActivity.this,OrderSucessActivity.class);
                                    mIntentRegInfo.putExtra("number", model.getData());
                                    mIntentRegInfo.putExtra("price", total_money*100);
                                    mIntentRegInfo.putExtra("money",price);
                                    startActivity(mIntentRegInfo);
                                    finish();
                                }
                            }

                        } else {
                            ToastUtil.showShort(WashCarSubmitActivity.this, NetRequestUtil.requestsError(response, "提交订单失败"));

                        }
                    }

                });
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    /**
     * 跳转相关页功能
     *
     * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {

        startActivity(new Intent(WashCarSubmitActivity.this, class1));

    }
}
